<template>
	<tm-app ref="app">
		<tm-navbar title="基本信息维护" color="orange" linear="right" beforeBack="true" hideHome="true"></tm-navbar>

		<tm-form v-if="showflag" @submit="confirm" v-model="entity" ref="form" :label-width="190">
			<!--
			<tm-divider align="left" label="身份证图片(带身份号码面)"></tm-divider>
			<tm-upload color="orange" :onStart="onZmStart" :imageHeight="200" :rows="1" v-model="zmlist" showSort
				:fileType="['camera']" :default-value="zmlist" ref="up" :onSuccessAfter="zmtest" :width="636"
				maxFile="1" :show-status="false" url="https://www.zhaobangyang.cn/wx/bs/upload">
				<template v-slot:icon>
					<tm-text color="orange" label="身份证(带身份号码面)"></tm-text>
				</template>
			</tm-upload>
			<tm-divider align="left" label="身份证图片(带国徽面)"></tm-divider>
			<tm-upload color="orange" :onStart="onStart" :imageHeight="200" :rows="1" v-model="list"
				:fileType="['camera']" showSort :default-value="list" ref="up" :onSuccessAfter="zmtest" :width="636"
				maxFile="1" :show-status="false" url="https://www.zhaobangyang.cn/wx/bs/upload">
				<template v-slot:icon>
					<tm-text color="orange" label="身份证(带国徽面)"></tm-text>
				</template>
			</tm-upload>
			-->

			<!--
			<tm-divider align="left" label="基本信息"></tm-divider>
			<tm-input v-model="entity.name" required prefixLabel="姓名:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			
			<tm-input v-model="entity.cardno" required prefixLabel="身份证号:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			
			<tm-divider align="left" label="学业信息"></tm-divider>
			<tm-input v-model="entity.school" required prefixLabel="就读/毕业院校:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			<tm-input v-model="entity.subject" required prefixLabel="专业:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			-->
			<!--
			<tm-divider align="left" label="校园卡等图片"></tm-divider>
			<tm-upload color="orange" :onStart="onXyStart" :imageHeight="200" :rows="1" v-model="xsklist"
					:fileType="['camera']" showSort :default-value="xsklist" ref="up" :onSuccessAfter="zmtest" :width="636"
					maxFile="1" :show-status="false" url="https://www.zhaobangyang.cn/wx/bs/upload">
					<template v-slot:icon>
						<tm-text color="orange" label="校园卡等证明图片"></tm-text>
					</template>
				</tm-upload>
			
			<tm-divider align="left" label="验证"></tm-divider>
			<tm-input v-model.lazy="entity.mobile" required prefixLabel="联系方式:" :margin="[0,10]"
				focusColor="orange"></tm-input>
			<tm-input v-model="entity.code" required @search="sendMessage()" prefixLabel="验证码:" focusColor="orange"
				:margin="[0,10]" searchLabel="获取"></tm-input>-->
			<tm-form-item required label="姓名" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.name" :transprent="true" :showBottomBotder="false"
					placeholder="请输入姓名"></tm-input>
			</tm-form-item>
			<tm-form-item required label="身份证号" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.cardno" :transprent="true" :showBottomBotder="false"
					placeholder="请输入身份证号"></tm-input>
			</tm-form-item>
			<tm-form-item required label="联系方式" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.mobile" :transprent="true" :showBottomBotder="false"
					placeholder="请输入联系方式" @search="sendMessage()" focusColor="orange"></tm-input>
			</tm-form-item>
			<tm-form-item label="院校" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.school" :transprent="true" :showBottomBotder="false"
					placeholder="请输入就读/毕业院校" disabled searchLabel="选择院校" focusColor="orange" @search="selSchool()"></tm-input>
			</tm-form-item>
			<tm-form-item label="专业" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.subject" :transprent="true" :showBottomBotder="false"
					placeholder="请输入专业"></tm-input>
			</tm-form-item>
			<tm-form-item label="自我介绍" labelWidth="0">
				<tm-input v-model="entity.remark" type="textarea" :transprent="true" :showBottomBotder="false"
					placeholder="请输入自我介绍" height="290"></tm-input>
			</tm-form-item>
			<tm-form-item label="展示照片" labelWidth="0">
				<tm-upload color="orange" :onStart="onTpStart" :imageHeight="200" :rows="1" v-model="zplist"
					showSort :default-value="zplist" ref="up" :onSuccessAfter="zmtest"
					:width="336" maxFile="1" :show-status="false" url="https://www.zhaobangyang.cn/wx/bs/upload">
					<template v-slot:icon>
						<tm-text color="orange" label="展示到帮手详情中,需要图片格式:jpg,比例是3:4"></tm-text>
					</template>
				</tm-upload>
			</tm-form-item>
			<tm-form-item label="证件上传" labelWidth="0">
				<tm-upload color="orange" :onStart="onXyStart" :imageHeight="200" :rows="1" v-model="xsklist"
					showSort :default-value="xsklist" ref="up" :onSuccessAfter="zmtest"
					:width="336" maxFile="1" :show-status="false" url="https://www.zhaobangyang.cn/wx/bs/upload">
					<template v-slot:icon>
						<tm-text color="orange" label="上传校园卡等证明图片"></tm-text>
					</template>
				</tm-upload>
			</tm-form-item>


			
			<tm-form-item v-if="false" label="验证码" labelWidth="0">
				<tm-input :inputPadding="[0, 0]" v-model="entity.code" :transprent="true" :showBottomBotder="false"
					placeholder="请输入验证码"></tm-input>
			</tm-form-item>
			<tm-form-item :border="false">
				<view class=" flex flex-row">
					<view class="flex-1 mr-32">
						<tm-button form-type="submit" color="orange" label="更新提交" followTheme="true" block></tm-button>
					</view>
				</view>
			</tm-form-item>
			<tm-form-item v-if="false" :border="false">
				<view class=" flex flex-row">
					<tm-checkbox @change="allChange" color="orange"
						label="请认真阅读并了解注意事项，并同意《用户服务协议》及《隐私政策》"></tm-checkbox>
				</view>
			</tm-form-item>
		</tm-form>

		<tm-result v-if="!showflag" :showBtn="false" title="审核中" subTitle="正在审核中,请稍后....." color="red"
			status="lock"></tm-result>
		<tm-drawer ref="calendarView" :placement="pos" v-model:show="showWin" hideCancel="true" okText="关闭" okColor="red">
			<view class="flex-row flex flex-wrap">
				<view v-for="(item,index) in slist" :key="index">
					<tm-tag color="orange" size="m" @click="selCheckSchool(item)" :label="item.name"></tm-tag>
				</view>
			</view>
			
		</tm-drawer>
		
		<tm-message ref="msg" :lines="5"></tm-message>
	</tm-app>
</template>

<script lang="ts" setup>
	import { ref, nextTick } from "vue";
	import { onLoad } from "@dcloudio/uni-app";
	import { isPhone, isEmpty, isIdCard } from "@/tmui/tool/function/util";
	import tmMessage from "@/tmui/components/tm-message/tm-message.vue";
	import { getcode, savebs, queryCount, getBsByWxid } from '@/api/bs';
	import { saveJzZmSfz, saveJzFmSfz, getOcrDetail, saveTpImg } from '@/api/jz'
	import { schoolNameList } from '@/api/search'

	const msg = ref<InstanceType<typeof tmMessage> | null>(null)
	const placement = ref('top')
	const userid = ref('');
	const showflag = ref(true);
	const xyflag = ref(false);
	const list = ref([]);
	const zmlist = ref([]);
	const xsklist = ref([]);
	const zplist = ref([]);
	const selab = ref("获取验证码");
	const entity = ref({
		name: "",
		cardno: "",
		school: "",
		subject: "",
		mobile: "",
		code: "",
		wxid: "",
		zmsfz: "",
		fmsfz: "",
		xszImg: "",
		img: "",
		remark: "",
		schoolId: ""
	});
	const imgbase = ref("");
	const msgFlag = ref(false);
	const showWin = ref(false)
	const pos = ref('bottom')
	const slist = ref([]);

	onLoad(() => {
		userid.value = uni.getStorageSync("userid");
		// console.log('初始化程序加载数据！', userid.value);
		if (isEmpty(userid.value)) {
			uni.redirectTo({
				url: '/pages/auth/auth'
			})
		} else {
			entity.value.wxid = userid.value;
			// 进行获取用户是否填报过
			// querybs();
		}
		schoolList();
		loadIsBs();
	})
	
	const selCheckSchool = async(item:any) => {
		console.log(JSON.stringify(item));
		entity.value.school = item.name;
		entity.value.schoolId = item.id;
		showWin.value = false;
	}
	
	const selSchool = async() => {
		showWin.value = true;
	}
	
	const schoolList = async () => {
		const result = await schoolNameList();
		// console.log(JSON.stringify(result));
		slist.value = result;
	}

	const zmtest = (item : any) => {
		let d = item.response;
		let isOk = true
		try {
			let p = JSON.parse(d)
			if (p?.code !== 0) {
				isOk = false;
			}
		} catch (e) {
			isOk = false;
		}

		return isOk;
	}
	// ---------------------上传身份证正面信息并获取基本信息----------------------------------
	const onZmStart = (item : any) => {
		imgToBase64(item.url);
		return true;
	}
	// 图片转base64方法
	const imgToBase64 = async (url : string) => {
		// #ifdef MP-WEIXIN
		uni.getFileSystemManager().readFile({
			filePath: url, // 选择图片返回的相对路径
			encoding: 'base64', // 编码格式
			success: res => { // 成功的回调
				// console.log(res, '返回结果');
				imgbase.value = `data:image/jpeg;base64,${res.data}`;
				// 进行保存上传图片
				saveZmSfz();
			},
			fail: (e) => {
				console.log("图片转换失败");
			}
		})
		// #endif
	}
	// 身份证正面保存
	const saveZmSfz = async () => {
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveJzZmSfz(param);
		entity.value.zmsfz = result.url;
		// 通过上传的身份证图片，识别身份证信息
		loadOcrDetail();
	}
	const loadOcrDetail = async () => {
		let param = { "url": entity.value.zmsfz };
		const result = await getOcrDetail(param);
		console.log(JSON.stringify(result));
		entity.value.cardno = result.msg.id;
		entity.value.name = result.msg.name;
	}

	// -----------------------身份证反面上传-------------------------------
	const onStart = (item : any) => {
		imgFmToBase64(item.url, '1');
		return true;
	}
	// 身份证反面保存
	const saveFmSfz = async () => {
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveJzFmSfz(param);
		entity.value.fmsfz = result.url;
	}

	// -----------------------校园卡等图片上传-------------------------------
	const onXyStart = (item : any) => {
		imgFmToBase64(item.url, '2');
		return true;
	}
	const onTpStart = (item : any) => {
		imgFmToBase64(item.url, '3');
		return true;
	}
	// 身份证反面保存
	const saveonXyKImg = async () => {
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveJzFmSfz(param);
		entity.value.xszImg = result.url;
	}
	
	const saveonTpImg = async() => { // ysxm
		let param = { "base": imgbase.value, "wxid": userid.value };
		const result = await saveTpImg(param);
		entity.value.img = result.url;
	}








	// 图片转base64方法
	const imgFmToBase64 = async (url : string, status : string) => {
		// #ifdef MP-WEIXIN
		uni.getFileSystemManager().readFile({
			filePath: url, // 选择图片返回的相对路径
			encoding: 'base64', // 编码格式
			success: res => { // 成功的回调
				// console.log(res, '返回结果');
				imgbase.value = `data:image/jpeg;base64,${res.data}`;
				// 进行保存上传图片
				if (status === '1') {
					saveFmSfz();
				}
				if (status === '2') {
					saveonXyKImg();
				}
				if (status === '3') {
					saveonTpImg();
				}
			},
			fail: (e) => {
				console.log("图片转换失败");
			}
		})
		// #endif
	}


	const loadIsBs = async () => {
		let param = { "wxid": userid.value }
		const result = await getBsByWxid(param);
		console.log(result);
		entity.value = result;
		// if (!isEmpty(result.id)) {
		// 	uni.setStorageSync("code", "0");
		// 	msg.value.show({ model: 'success',text: '绑定成功' })
		// 	uni.redirectTo({
		// 		url: '/pages/index/my'
		// 	})
		// }
	}


	function allChange(e : any) {
		// console.log(e);
		xyflag.value = e;
	}

	const querybs = async () => {
		let param = { "wxid": userid.value };
		const jg = await queryCount(param);
		console.log("结果：：：", JSON.stringify(jg));
		if (jg.code === "400") {
			showflag.value = false;
		}
	}


	function confirm() {
		// if (!xyflag.value) {
		// 	msg.value.show({ model: 'error',text: '请同意协议' })
		// 	return false;
		// }
		if (isEmpty(entity.value.name)) {
			msg.value.show({ model: 'error',text: '姓名不能为空' })
			return false;
		}
		// if (isEmpty(entity.value.cardno)) {
		// 	nextTick(() => {
		// 		msg.value.show({ model: 'error', label: "证件号码不能为空！" })
		// 	})
		// 	return false;
		// }
		// if (isEmpty(entity.value.school)) {
		// 	nextTick(() => {
		// 		msg.value.show({ model: 'error', label: "就读/毕业院校不能为空！" })
		// 	})
		// 	return false;
		// }
		// if (isEmpty(entity.value.subject)) {
		// 	nextTick(() => {
		// 		msg.value.show({ model: 'error', label: "专业不能为空！" })
		// 	})
		// 	return false;
		// }
		if (isEmpty(entity.value.mobile)) {
			msg.value.show({ model: 'error',text: '联系方式不能为空' })
			return false;
		}
		// if (isEmpty(entity.value.code)) {
		// 	msg.value.show({ model: 'error',text: '验证码不能为空' })
		// 	return false;
		// }
		// if (!isIdCard(entity.value.cardno)) {
		// 	nextTick(() => {
		// 		msg.value.show({ model: 'error', label: "请输入正确的证件号码！" })
		// 	})
		// 	return false;
		// }


		savebangshou();


		return true;
	}




	const savebangshou = async () => {
		const result = await savebs(entity.value);
		// console.log("返回结果：",JSON.stringify(result));
		if (result.code === "200") {
			msg.value.show({ model: 'success',text: '更新成功' })
			// showflag.value = false;
			// uni.setStorageSync("code", "0");
			uni.redirectTo({
				url: 'pages/index/my'
			})
		} else if (result.code === "400") {
			msg.value.show({ model: 'error',text: result.msg })
		}
	}





	function sendMessage() {
		if (msgFlag.value) {
			return false;
		}
		if (isEmpty(entity.value.mobile)) {
			msg.value.show({ model: 'error',text: "联系方式不能为空！" })
			return false;
		}
		if (!isPhone(entity.value.mobile)) {
			msg.value.show({ model: 'error',text: "请填写正确的联系方式！" })
			return false;
		}
		loadUserData();
		djsbtn(30);
		return true;
	}

	function djsbtn(seconds : any) {
		msgFlag.value = true;
		let remainingTime = seconds;
		const interval = setInterval(() => {
			remainingTime -= 1;
			if (remainingTime === 0) {
				clearInterval(interval);
				// console.log('Finished'); ysxm
				selab.value = `获取验证码`;
				msgFlag.value = false;
			} else {
				// console.log(remainingTime);
				selab.value = `等待${remainingTime}秒`;
			}
		}, 1000);
	}

	const loadUserData = async () => {
		let param = { "mobile": entity.value.mobile };
		const result = await getcode(param);
		console.log("返回结果：", JSON.stringify(result));
		if (result.code === "200") {
			msg.value.show({ model: 'success',text: '短信发送成功！' })
		} else if (result.code === "400") {
			msg.value.show({ model: 'error',text: result.msg })
		}
	}
</script>

<style>

</style>